package com.ruoyi.framework.interceptor;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class TokenValidationInterceptor implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求中的token
        String token = request.getHeader(Constants.TOKEN_HEADER);
        
        // 如果token为空
        if (StringUtils.isEmpty(token)) {
            log.warn("接收到无效Token的请求");
            handleUnauthorizedAccess(response);
            return false;
        }

        try {
            // 验证token
            LoginUser loginUser = tokenService.getLoginUser(request);
            
            // 如果token无效或已过期
            if (loginUser == null) {
                log.warn("Token验证失败");
                handleUnauthorizedAccess(response);
                return false;
            }

            // 可以进行额外的权限验证
            return true;
        } catch (Exception e) {
            log.error("Token验证发生异常", e);
            handleUnauthorizedAccess(response);
            return false;
        }
    }

    /**
     * 处理未授权访问
     */
    private void handleUnauthorizedAccess(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(401);
        response.getWriter().write(
            "{\"msg\":\"Unauthorized\",\"code\":401,\"data\":null}"
        );
    }
}